﻿using Microsoft.EntityFrameworkCore;
using StudentManagement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

namespace StudentManagement.Infrastructure.Repositories
{
    public class RepositoryBase<T> : IRepository<T> where T : BaseEntity
    {
        protected readonly ApplicationDbContext dbContext; // 数据库上下文

        // 从数据库上下文中获取领域模型
        public DbSet<T> Table;

        public RepositoryBase(ApplicationDbContext dbContext)
        {
            this.dbContext = dbContext;
            Table = dbContext.Set<T>();
        }

        public IQueryable<T> GetAll()
        {
            return Table.AsQueryable();
        }

        public IEnumerable<T> GetAllAsList()
        {
            return Table.AsEnumerable();
        }

        public T Get(int id)
        {
            return Table.SingleOrDefault(s => s.Id == id);
        }


        public T Insert(T entity)
        {
            if (entity == null) {
                throw new ArgumentNullException("Entity is null.");
            }
            Table.Add(entity);
            dbContext.SaveChanges();

            return entity;
        }

        public T Update(T entity)
        {
            if (entity == null) {
                throw new ArgumentNullException("Entity is null.");
            }

            AttachIfNot(entity);
            dbContext.Entry(entity).State = EntityState.Modified;
            dbContext.SaveChanges();

            return entity;
        }

        public void Delete(T entity)
        {
            if (entity == null) {
                throw new ArgumentNullException("Entity is null.");
            }
            Table.Remove(entity);
            dbContext.SaveChanges();
        }

        public int Count()
        {
            return this.GetAll().Count();
        }

        public T Single(Expression<Func<T, bool>> predicate)
        {
            return this.GetAll().Single(predicate);
        }

        protected virtual void AttachIfNot(T entity)
        {

            var entry = dbContext.ChangeTracker.Entries()
                .FirstOrDefault(ent => ent.Entity == entity);

            if (entry != null) {
                return;
            }

            Table.Attach(entity);
        }
    }       
}
